package handlers

import (
	"fmt"
	"jianianhua-server/database"
	"jianianhua-server/models"
	"jianianhua-server/services"
	"jianianhua-server/utils"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type AuthHandler struct {
	wechatService *services.WechatService
	roleService   *services.RoleService
}

// LoginRequest 登录请求（保留用于兼容性，但不再使用）
type LoginRequest struct {
	Phone    string `json:"phone" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// UpdateProfileRequest 更新个人信息请求
type UpdateProfileRequest struct {
	Nickname string `json:"nickname" binding:"required"`
	Avatar   string `json:"avatar"`
	Phone    string `json:"phone"`
	Gender   int    `json:"gender"`
	Country  string `json:"country"`
	Province string `json:"province"`
	City     string `json:"city"`
	Language string `json:"language"`
}


func NewAuthHandler(wechatService *services.WechatService) *AuthHandler {
	return &AuthHandler{
		wechatService: wechatService,
		roleService:   services.NewRoleService(),
	}
}

// WechatLogin 微信登录
func (h *AuthHandler) WechatLogin(c *gin.Context) {
	var req services.WechatLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.BadRequestResponse(c, "参数错误: "+err.Error())
		return
	}

	resp, err := h.wechatService.Login(req)
	if err != nil {
		utils.InternalServerErrorResponse(c, "登录失败: "+err.Error())
		return
	}

	responseData := gin.H{
		"token":      resp.Token,
		"user_info":  resp.User,
		"expires_in": resp.ExpiresIn,
	}
	
	utils.SuccessResponse(c, responseData)
}

// UpdateUserInfo 更新用户信息
func (h *AuthHandler) UpdateUserInfo(c *gin.Context) {
	userID, exists := utils.GetUserIDFromContext(c)
	if !exists {
		utils.UnauthorizedResponse(c, "用户未登录")
		return
	}

	var req UpdateProfileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.BadRequestResponse(c, "参数错误: "+err.Error())
		return
	}


	// 获取用户信息
	var user models.User
	
	// 先尝试不使用软删除的查询
	if err := database.DB.Unscoped().First(&user, userID).Error; err != nil {
		// 再尝试普通查询
		if err := database.DB.First(&user, userID).Error; err != nil {
			utils.InternalServerErrorResponse(c, "获取用户信息失败")
			return
		}
	}

	// 更新用户信息
	if err := database.DB.Exec(`
		UPDATE users SET 
			nickname = ?, 
			avatar = ?, 
			phone = ?,
			gender = ?, 
			country = ?, 
			province = ?, 
			city = ?, 
			language = ?, 
			updated_at = ?
		WHERE id = ?
	`, req.Nickname, req.Avatar, req.Phone, req.Gender, req.Country, req.Province, req.City, req.Language, time.Now(), userID).Error; err != nil {
		utils.InternalServerErrorResponse(c, "更新用户信息失败: "+err.Error())
		return
	}


	// 返回更新后的用户信息
	utils.SuccessResponse(c, gin.H{
		"message": "用户信息更新成功",
		"user": gin.H{
			"id":       user.ID,
			"nickname": req.Nickname, // Use req.Nickname as it's the updated value
			"avatar":   req.Avatar,   // Use req.Avatar as it's the updated value
			"phone":    req.Phone,    // Use req.Phone as it's the updated value (can be nil)
			"gender":   req.Gender,
			"country":  req.Country,
			"province": req.Province,
			"city":     req.City,
			"language": req.Language,
		},
	})
}

// UploadAvatar 上传头像
func (h *AuthHandler) UploadAvatar(c *gin.Context) {
	userID, exists := utils.GetUserIDFromContext(c)
	if !exists {
		utils.UnauthorizedResponse(c, "用户未登录")
		return
	}

	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		utils.BadRequestResponse(c, "获取上传文件失败: "+err.Error())
		return
	}

	// 检查文件类型
	if !utils.IsImageFile(file.Filename) {
		utils.BadRequestResponse(c, "只支持图片格式")
		return
	}

	// 检查文件大小 (5MB)
	if file.Size > 5*1024*1024 {
		utils.BadRequestResponse(c, "文件大小不能超过5MB")
		return
	}

	// 生成文件名
	filename := utils.GenerateFileName("avatar", file.Filename)
	filepath := "uploads/avatars/" + filename

	// 确保目录存在
	if err := utils.EnsureDir("uploads/avatars/"); err != nil {
		utils.InternalServerErrorResponse(c, "创建目录失败")
		return
	}

	// 保存文件
	if err := c.SaveUploadedFile(file, filepath); err != nil {
		utils.InternalServerErrorResponse(c, "保存文件失败: "+err.Error())
		return
	}

	// 更新用户头像
	var user models.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		utils.InternalServerErrorResponse(c, "获取用户信息失败")
		return
	}

	// 生成完整的HTTPS URL
	host := c.Request.Host
	if host == "" {
		host = "jianianhua.asia"
	}
	avatarURL := fmt.Sprintf("https://%s/%s", host, filepath)
	
	user.Avatar = avatarURL
	if err := database.DB.Save(&user).Error; err != nil {
		utils.InternalServerErrorResponse(c, "更新头像失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, gin.H{
		"message": "头像上传成功",
		"url":     avatarURL,
	})
}

// GetUserInfo 获取用户信息
func (h *AuthHandler) GetUserInfo(c *gin.Context) {
	userID, exists := utils.GetUserIDFromContext(c)
	if !exists {
		utils.UnauthorizedResponse(c, "用户未登录")
		return
	}

	// 获取用户详细信息
	var user models.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.UnauthorizedResponse(c, "用户不存在，请重新登录")
		} else {
			utils.InternalServerErrorResponse(c, "获取用户信息失败")
		}
		return
	}

	// 检查是否为管理员
	isAdmin := user.Role == "admin"

	utils.SuccessResponse(c, gin.H{
		"id":       user.ID,
		"nickname": user.Nickname,
		"avatar":   user.Avatar,
		"phone":    user.Phone, // Can be nil
		"role":     user.Role,
		"isAdmin":  isAdmin,
		"wechat_user": gin.H{
			"nickname":   user.Nickname,
			"avatar_url": user.Avatar,
			"gender":     user.Gender,
			"country":    user.Country,
			"province":   user.Province,
			"city":     user.City,
		},
	})
}

// DeleteUser 删除用户账号
func (h *AuthHandler) DeleteUser(c *gin.Context) {
	userID, exists := utils.GetUserIDFromContext(c)
	if !exists {
		utils.UnauthorizedResponse(c, "用户未登录")
		return
	}

	// 获取用户信息
	var user models.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.UnauthorizedResponse(c, "用户不存在")
		} else {
			utils.InternalServerErrorResponse(c, "获取用户信息失败")
		}
		return
	}

	// 检查是否为管理员，管理员不能删除自己
	if user.Role == "admin" {
		utils.BadRequestResponse(c, "管理员账号不能删除")
		return
	}

	// 开始事务
	tx := database.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 删除用户相关的预约记录
	if err := tx.Where("user_id = ?", userID).Delete(&models.Appointment{}).Error; err != nil {
		tx.Rollback()
		utils.InternalServerErrorResponse(c, "删除预约记录失败: "+err.Error())
		return
	}

	// 删除用户设置
	if err := tx.Where("user_id = ?", userID).Delete(&models.UserSettings{}).Error; err != nil {
		tx.Rollback()
		utils.InternalServerErrorResponse(c, "删除用户设置失败: "+err.Error())
		return
	}

	// 删除用户账号（软删除）
	if err := tx.Delete(&user).Error; err != nil {
		tx.Rollback()
		utils.InternalServerErrorResponse(c, "删除用户账号失败: "+err.Error())
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		utils.InternalServerErrorResponse(c, "删除操作失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, gin.H{
		"message": "账号已成功删除",
	})
}

// Login 用户登录（已废弃，只保留微信登录）
// func (h *AuthHandler) Login(c *gin.Context) {
// 	// 此方法已废弃，请使用微信登录
// }


